// 全局变量和常量
const API_BASE_URL = '/api/v1/delivery';
let currentDeliveryPerson = null;
let currentOrderNumber = null;
let mapInstance = null;
let currentLocationMapInstance = null;
let orderRouteMapInstance = null;

// DOM 元素引用
const myOrdersView = document.getElementById('myOrdersView');
const orderDetailView = document.getElementById('orderDetailView');
const profileView = document.getElementById('profileView');
const ordersList = document.getElementById('ordersList');
const ordersLoader = document.getElementById('ordersLoader');
const noOrdersMessage = document.getElementById('noOrdersMessage');
const orderDetailsCard = document.getElementById('orderDetailsCard');
const logisticsTraces = document.getElementById('logisticsTraces');
const updateStatusForm = document.getElementById('updateStatusForm');
const newStatusSelect = document.getElementById('newStatus');
const locationInput = document.getElementById('location');
const descriptionInput = document.getElementById('description');
const backToOrdersBtn = document.getElementById('backToOrdersBtn');
const myOrdersLink = document.getElementById('myOrdersLink');
const myProfileLink = document.getElementById('myProfileLink');
const profileInfo = document.getElementById('profileInfo');
const deliveryPersonName = document.getElementById('deliveryPersonName');
const deliveryPersonStatus = document.getElementById('deliveryPersonStatus');
const statusIndicator = document.getElementById('statusIndicator');
const statusDropdown = document.getElementById('statusDropdown');
const updateLocationBtn = document.getElementById('updateLocationBtn');
const alertArea = document.getElementById('alertArea');
const mainLoader = document.getElementById('mainLoader');
const availableOrdersView = document.getElementById('availableOrdersView');
const availableOrdersList = document.getElementById('availableOrdersList');
const availableOrdersLoader = document.getElementById('availableOrdersLoader');
const noAvailableOrdersMessage = document.getElementById('noAvailableOrdersMessage');
const availableOrdersLink = document.getElementById('availableOrdersLink');

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化页面
    initPage();

    // 事件监听器
    myOrdersLink.addEventListener('click', showMyOrdersView);
    myProfileLink.addEventListener('click', showProfileView);
    availableOrdersLink.addEventListener('click', showAvailableOrdersView);
    backToOrdersBtn.addEventListener('click', showMyOrdersView);
    updateStatusForm.addEventListener('submit', handleUpdateStatus);
    updateLocationBtn.addEventListener('click', updateCurrentLocation);

    // 状态下拉菜单点击事件
    document.querySelectorAll('.dropdown-item').forEach(item => {
        item.addEventListener('click', function(e) {
            e.preventDefault();
            const status = this.getAttribute('data-status');
            updateDeliveryPersonStatus(status);
        });
    });
});

// 初始化页面
async function initPage() {
    showLoader(true);
    try {
        // 获取当前配送员信息
        await fetchDeliveryPersonInfo();
        // 初始化当前位置地图
        initCurrentLocationMap();
        // 加载订单列表
        await loadMyOrders();
        // 加载可接单订单列表
        await loadAvailableOrders();
        // 连接WebSocket
        connectWebSocket();
        // 默认显示订单列表视图
        showMyOrdersView();
    } catch (error) {
        console.error('初始化页面失败:', error);
        showAlert('初始化页面失败，请刷新页面重试。', 'danger');
    } finally {
        showLoader(false);
    }
}

// 获取当前配送员信息
async function fetchDeliveryPersonInfo() {
    try {
        const response = await fetchAuthenticatedApi(`${API_BASE_URL}/me`);
        if (response.ok) {
            currentDeliveryPerson = await response.json();
            updateDeliveryPersonUI();
        } else {
            throw new Error('获取配送员信息失败');
        }
    } catch (error) {
        console.error('获取配送员信息失败:', error);
        showAlert('获取配送员信息失败，请刷新页面重试。', 'danger');
    }
}

// 更新配送员UI
function updateDeliveryPersonUI() {
    if (currentDeliveryPerson) {
        deliveryPersonName.textContent = currentDeliveryPerson.name;
        deliveryPersonStatus.textContent = formatDeliveryPersonStatus(currentDeliveryPerson.status);
        deliveryPersonStatus.className = `badge ${getStatusBadgeClass(currentDeliveryPerson.status)} ms-1`;
        statusIndicator.className = `status-indicator ${getStatusIndicatorClass(currentDeliveryPerson.status)}`;
    }
}

// 加载我的订单
async function loadMyOrders() {
    ordersLoader.style.display = 'block';
    noOrdersMessage.style.display = 'none';
    ordersList.innerHTML = '';

    try {
        const response = await fetchAuthenticatedApi(`${API_BASE_URL}/orders`);
        if (response.ok) {
            const orders = await response.json();
            displayOrders(orders);
        } else {
            throw new Error('获取订单列表失败');
        }
    } catch (error) {
        console.error('获取订单列表失败:', error);
        showAlert('获取订单列表失败，请刷新页面重试。', 'danger');
    } finally {
        ordersLoader.style.display = 'none';
    }
}

// 显示订单列表
function displayOrders(orders) {
    if (!orders || orders.length === 0) {
        noOrdersMessage.style.display = 'block';
        return;
    }

    const ordersHtml = orders.map(order => `
        <div class="card order-card">
            <div class="card-header bg-light d-flex justify-content-between align-items-center">
                <h5 class="mb-0">订单号: ${order.orderNumber}</h5>
                <span class="badge ${getOrderStatusBadgeClass(order.status)}">${formatOrderStatus(order.status)}</span>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <p class="mb-2"><i class="bi bi-box-seam me-2"></i><strong>物品:</strong> ${order.itemDescription || 'N/A'}</p>
                        <p class="mb-2"><i class="bi bi-rulers me-2"></i><strong>重量:</strong> ${order.weight ? order.weight + ' kg' : 'N/A'}</p>
                    </div>
                    <div class="col-md-6">
                        <p class="mb-2"><i class="bi bi-calendar-plus me-2"></i><strong>创建时间:</strong> ${formatDate(order.creationTime)}</p>
                        <p class="mb-2"><i class="bi bi-cash-coin me-2"></i><strong>费用:</strong> ${order.calculatedFee ? '¥' + order.calculatedFee.toFixed(2) : 'N/A'}</p>
                    </div>
                </div>
                <div class="row mt-2">
                    <div class="col-md-6">
                        <h6 class="card-subtitle mb-1 text-muted"><i class="bi bi-person-up me-1"></i>发货方</h6>
                        <p class="card-text mb-1 small">${formatAddress(order.shipperInfo)}</p>
                    </div>
                    <div class="col-md-6">
                        <h6 class="card-subtitle mb-1 text-muted"><i class="bi bi-person-down me-1"></i>收货方</h6>
                        <p class="card-text mb-1 small">${formatAddress(order.recipientInfo)}</p>
                    </div>
                </div>
                <div class="text-end mt-3">
                    <button class="btn btn-sm btn-outline-primary view-order-btn" data-order-number="${order.orderNumber}">
                        <i class="bi bi-eye"></i> 查看详情
                    </button>
                </div>
            </div>
        </div>
    `).join('');

    ordersList.innerHTML = ordersHtml;

    // 添加查看详情按钮点击事件
    document.querySelectorAll('.view-order-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const orderNumber = this.getAttribute('data-order-number');
            viewOrderDetail(orderNumber);
        });
    });
}

// 查看订单详情
async function viewOrderDetail(orderNumber) {
    if (!orderNumber) return;

    showLoader(true);
    try {
        // 保存当前订单号
        currentOrderNumber = orderNumber;

        // 获取订单详情
        const orderResponse = await fetchAuthenticatedApi(`/api/v1/orders/${orderNumber}`);
        if (!orderResponse.ok) {
            throw new Error('获取订单详情失败');
        }
        const order = await orderResponse.json();

        // 获取物流轨迹
        const tracesResponse = await fetchAuthenticatedApi(`${API_BASE_URL}/orders/${orderNumber}/traces`);
        let traces = [];
        if (tracesResponse.ok) {
            traces = await tracesResponse.json();
        }

        // 获取路径坐标
        const pathResponse = await fetchAuthenticatedApi(`/api/v1/orders/${orderNumber}/path`);
        let pathCoordinates = [];
        if (pathResponse.ok) {
            pathCoordinates = await pathResponse.json();
        }

        // 显示订单详情
        displayOrderDetails(order);
        // 显示物流轨迹
        displayLogisticsTraces(traces);
        // 更新状态选择框
        updateStatusOptions(order.status);
        // 初始化路线地图
        initOrderRouteMap(pathCoordinates);
        // 自动获取当前位置并填充
        fillCurrentLocation();
        // 显示订单详情视图
        showOrderDetailView();
    } catch (error) {
        console.error('查看订单详情失败:', error);
        showAlert('查看订单详情失败: ' + error.message, 'danger');
    } finally {
        showLoader(false);
    }
}

// 显示订单详情
function displayOrderDetails(order) {
    const statusBadgeClass = getOrderStatusBadgeClass(order.status);
    const orderHtml = `
        <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
            <h5 class="mb-0">订单号: ${order.orderNumber}</h5>
            <span class="badge ${statusBadgeClass}">${formatOrderStatus(order.status)}</span>
        </div>
        <ul class="list-group list-group-flush">
            <li class="list-group-item"><strong><i class="bi bi-card-text me-2"></i>物品描述:</strong> ${order.itemDescription || 'N/A'}</li>
            <li class="list-group-item"><strong><i class="bi bi-rulers me-2"></i>重量:</strong> ${order.weight !== null ? order.weight + ' kg' : 'N/A'}</li>
            <li class="list-group-item"><strong><i class="bi bi-cash-coin me-2"></i>计算费用:</strong> ${order.calculatedFee !== null ? '¥' + order.calculatedFee.toFixed(2) : 'N/A'}</li>
            <li class="list-group-item"><strong><i class="bi bi-calendar-plus me-2"></i>创建时间:</strong> ${order.creationTime ? formatDate(order.creationTime) : 'N/A'}</li>
            ${order.pickupTime ? `<li class="list-group-item"><strong><i class="bi bi-box-arrow-in-up me-2"></i>揽收时间:</strong> ${formatDate(order.pickupTime)}</li>` : ''}
            ${order.deliveryTime ? `<li class="list-group-item"><strong><i class="bi bi-calendar-check me-2"></i>送达时间:</strong> ${formatDate(order.deliveryTime)}</li>` : ''}
        </ul>
        <div class="card-body pt-2">
            <h6 class="card-subtitle mt-3 mb-1 text-muted"><i class="bi bi-person-up me-1"></i>发货方</h6>
            <p class="card-text mb-3 small">${formatAddress(order.shipperInfo)}</p>
            <h6 class="card-subtitle mb-1 text-muted"><i class="bi bi-person-down me-1"></i>收货方</h6>
            <p class="card-text mb-1 small">${formatAddress(order.recipientInfo)}</p>
        </div>
    `;

    orderDetailsCard.innerHTML = orderHtml;
}

// 自动获取当前位置并填充表单
function fillCurrentLocation() {
    if (!navigator.geolocation) {
        console.warn('浏览器不支持地理位置功能');
        return;
    }

    navigator.geolocation.getCurrentPosition(
        async (position) => {
            try {
                const longitude = position.coords.longitude;
                const latitude = position.coords.latitude;
                
                // 使用经纬度获取地址描述（可以使用第三方API如高德地图或百度地图）
                // 这里简化处理，直接使用经纬度
                locationInput.value = `经度:${longitude.toFixed(6)}, 纬度:${latitude.toFixed(6)}`;
                
                // 如果有配送员当前位置，也可以直接使用
                if (currentDeliveryPerson && currentDeliveryPerson.currentLocation) {
                    locationInput.value = currentDeliveryPerson.currentLocation;
                }
            } catch (error) {
                console.error('获取位置信息失败:', error);
            }
        },
        (error) => {
            console.error('获取地理位置失败:', error);
        },
        {
            enableHighAccuracy: true,
            timeout: 10000,
            maximumAge: 0
        }
    );
}

// 显示物流轨迹
function displayLogisticsTraces(traces) {
    if (!traces || traces.length === 0) {
        logisticsTraces.innerHTML = '<p class="text-center">暂无物流轨迹</p>';
        return;
    }

    const tracesHtml = traces.map(trace => `
        <div class="trace-item">
            <div class="trace-time"><i class="bi bi-clock-history me-1"></i>${trace.timestamp ? formatDate(trace.timestamp) : '时间未知'}</div>
            <div class="trace-description">${trace.status ? formatOrderStatus(trace.status) : (trace.description || '状态未知')}</div>
            <div class="trace-details text-muted small">
                ${trace.location ? `<i class="bi bi-geo me-1"></i>地点: ${trace.location}` : ''}
                ${trace.operator ? `<span class="ms-2"><i class="bi bi-person-fill me-1"></i>操作员: ${trace.operator}</span>` : ''}
                ${(trace.status && trace.description && trace.description !== formatOrderStatus(trace.status)) ? `<span class="ms-2"><i class="bi bi-info-circle me-1"></i>备注: ${trace.description}</span>` : ''}
            </div>
        </div>
    `).join('');

    logisticsTraces.innerHTML = tracesHtml;
}

// 更新状态选择框
function updateStatusOptions(currentStatus) {
    // 清空选择框
    newStatusSelect.innerHTML = '';

    // 根据当前状态设置可选的下一状态
    const nextStatuses = getNextPossibleStatuses(currentStatus);
    nextStatuses.forEach(status => {
        const option = document.createElement('option');
        option.value = status;
        option.textContent = formatOrderStatus(status);
        newStatusSelect.appendChild(option);
    });

    // 如果没有可选状态，禁用表单
    if (nextStatuses.length === 0) {
        newStatusSelect.innerHTML = '<option value="">无可用状态更新</option>';
        updateStatusForm.querySelectorAll('input, textarea, select, button').forEach(el => el.disabled = true);
    } else {
        updateStatusForm.querySelectorAll('input, textarea, select, button').forEach(el => el.disabled = false);
    }
}

// 获取下一个可能的状态
function getNextPossibleStatuses(currentStatus) {
    switch (currentStatus) {
        case 'PENDING_PAYMENT':
            return ['PENDING_COLLECTION'];
        case 'PENDING_COLLECTION':
            return ['COLLECTED'];
        case 'COLLECTED':
            return ['TRANSPORTING'];
        case 'TRANSPORTING':
            return ['OUT_FOR_DELIVERY'];
        case 'OUT_FOR_DELIVERY':
            return ['SIGNED', 'DELIVERY_FAILED'];
        case 'DELIVERY_FAILED':
            return ['OUT_FOR_DELIVERY', 'CANCELLED'];
        case 'SIGNED':
            return ['COMPLETED'];
        default:
            return [];
    }
}

// 处理更新状态
async function handleUpdateStatus(event) {
    event.preventDefault();
    if (!currentOrderNumber) return;

    const newStatus = newStatusSelect.value;
    const location = locationInput.value.trim();
    const description = descriptionInput.value.trim();

    if (!newStatus) {
        showAlert('请选择新状态', 'warning');
        return;
    }

    if (!location) {
        showAlert('请输入当前位置', 'warning');
        return;
    }

    showLoader(true);
    try {
        const response = await fetchAuthenticatedApi(
            `${API_BASE_URL}/orders/${currentOrderNumber}/status?newStatus=${newStatus}&location=${encodeURIComponent(location)}&description=${encodeURIComponent(description)}`,
            {
                method: 'PUT'
            }
        );

        if (response.ok) {
            const updatedOrder = await response.json();
            showAlert('订单状态已更新', 'success');
            // 重新加载订单详情
            viewOrderDetail(currentOrderNumber);
        } else {
            const errorData = await response.json();
            throw new Error(errorData.message || '更新订单状态失败');
        }
    } catch (error) {
        console.error('更新订单状态失败:', error);
        showAlert('更新订单状态失败: ' + error.message, 'danger');
    } finally {
        showLoader(false);
    }
}

// 更新配送员状态
async function updateDeliveryPersonStatus(status) {
    showLoader(true);
    try {
        const response = await fetchAuthenticatedApi(
            `${API_BASE_URL}/status?status=${status}`,
            {
                method: 'PUT'
            }
        );

        if (response.ok) {
            const updatedPerson = await response.json();
            currentDeliveryPerson = updatedPerson;
            updateDeliveryPersonUI();
            showAlert(`状态已更新为: ${formatDeliveryPersonStatus(status)}`, 'success');
        } else {
            const errorData = await response.json();
            throw new Error(errorData || '更新状态失败');
        }
    } catch (error) {
        console.error('更新状态失败:', error);
        showAlert('更新状态失败: ' + error.message, 'danger');
    } finally {
        showLoader(false);
    }
}

// 更新当前位置
async function updateCurrentLocation() {
    if (!navigator.geolocation) {
        showAlert('您的浏览器不支持地理位置功能', 'warning');
        return;
    }

    showLoader(true);
    navigator.geolocation.getCurrentPosition(
        async (position) => {
            try {
                const longitude = position.coords.longitude;
                const latitude = position.coords.latitude;

                const response = await fetchAuthenticatedApi(
                    `${API_BASE_URL}/location?longitude=${longitude}&latitude=${latitude}`,
                    {
                        method: 'PUT'
                    }
                );

                if (response.ok) {
                    const updatedPerson = await response.json();
                    currentDeliveryPerson = updatedPerson;
                    updateCurrentLocationOnMap(longitude, latitude);
                    showAlert('位置已更新', 'success');
                } else {
                    const errorData = await response.json();
                    throw new Error(errorData || '更新位置失败');
                }
            } catch (error) {
                console.error('更新位置失败:', error);
                showAlert('更新位置失败: ' + error.message, 'danger');
            } finally {
                showLoader(false);
            }
        },
        (error) => {
            showLoader(false);
            console.error('获取地理位置失败:', error);
            let errorMessage = '获取地理位置失败';
            switch (error.code) {
                case error.PERMISSION_DENIED:
                    errorMessage += ': 用户拒绝了地理位置请求';
                    break;
                case error.POSITION_UNAVAILABLE:
                    errorMessage += ': 位置信息不可用';
                    break;
                case error.TIMEOUT:
                    errorMessage += ': 获取位置超时';
                    break;
                case error.UNKNOWN_ERROR:
                    errorMessage += ': 未知错误';
                    break;
            }
            showAlert(errorMessage, 'warning');
        },
        {
            enableHighAccuracy: true,
            timeout: 10000,
            maximumAge: 0
        }
    );
}

// 显示个人信息
function showProfileView() {
    myOrdersView.style.display = 'none';
    orderDetailView.style.display = 'none';
    profileView.style.display = 'block';
    myOrdersLink.classList.remove('active');
    myProfileLink.classList.add('active');

    // 显示个人信息
    if (currentDeliveryPerson) {
        const statusClass = getStatusBadgeClass(currentDeliveryPerson.status);
        const profileHtml = `
            <div class="mb-3">
                <h5 class="text-primary"><i class="bi bi-person-circle me-2"></i>${currentDeliveryPerson.name}</h5>
                <p class="text-muted mb-1"><i class="bi bi-telephone me-2"></i>${currentDeliveryPerson.phone || 'N/A'}</p>
                <p class="mb-3">
                    <span class="badge ${statusClass}">${formatDeliveryPersonStatus(currentDeliveryPerson.status)}</span>
                </p>
            </div>
            <hr>
            <div class="mb-3">
                <h6 class="text-muted">当前位置</h6>
                ${currentDeliveryPerson.currentLocation ? 
                    `<p><i class="bi bi-geo-alt me-1"></i>经度: ${currentDeliveryPerson.currentLocation[0].toFixed(6)}, 纬度: ${currentDeliveryPerson.currentLocation[1].toFixed(6)}</p>` : 
                    '<p class="text-muted">未设置位置</p>'}
            </div>
            <hr>
            <div>
                <h6 class="text-muted">账号信息</h6>
                <p class="mb-1"><i class="bi bi-calendar2-check me-2"></i>注册时间: ${currentDeliveryPerson.createdAt ? formatDate(currentDeliveryPerson.createdAt) : 'N/A'}</p>
                <p><i class="bi bi-calendar2-event me-2"></i>最后更新: ${currentDeliveryPerson.updatedAt ? formatDate(currentDeliveryPerson.updatedAt) : 'N/A'}</p>
            </div>
        `;
        profileInfo.innerHTML = profileHtml;
    } else {
        profileInfo.innerHTML = '<p class="text-center">加载个人信息中...</p>';
    }
    
    // 加载工作统计数据
    loadWorkStatistics();
}

// 显示我的订单视图
function showMyOrdersView() {
    myOrdersView.style.display = 'block';
    orderDetailView.style.display = 'none';
    profileView.style.display = 'none';
    myOrdersLink.classList.add('active');
    myProfileLink.classList.remove('active');
}

// 显示订单详情视图
function showOrderDetailView() {
    myOrdersView.style.display = 'none';
    orderDetailView.style.display = 'block';
    profileView.style.display = 'none';
    
    // 添加这一行，使页面滚动到顶部
    window.scrollTo(0, 0);
}

// 初始化当前位置地图
function initCurrentLocationMap() {
    if (typeof AMap === "undefined") {
        console.error("AMap SDK not loaded!");
        return;
    }

    if (currentLocationMapInstance) {
        currentLocationMapInstance.destroy();
    }

    currentLocationMapInstance = new AMap.Map('currentLocationMap', {
        resizeEnable: true,
        zoom: 13
    });

    // 如果有当前位置，在地图上显示
    if (currentDeliveryPerson && currentDeliveryPerson.currentLocation) {
        const longitude = currentDeliveryPerson.currentLocation[0];
        const latitude = currentDeliveryPerson.currentLocation[1];
        updateCurrentLocationOnMap(longitude, latitude);
    }
}

// 更新当前位置地图
function updateCurrentLocationOnMap(longitude, latitude) {
    if (!currentLocationMapInstance) return;

    // 清除现有标记
    currentLocationMapInstance.clearMap();

    // 添加新标记
    const marker = new AMap.Marker({
        position: new AMap.LngLat(longitude, latitude),
        title: '当前位置'
    });

    currentLocationMapInstance.add(marker);
    currentLocationMapInstance.setCenter([longitude, latitude]);
}

// 初始化订单路线地图
function initOrderRouteMap(pathCoordinates) {
    if (typeof AMap === "undefined") {
        console.error("AMap SDK not loaded!");
        return;
    }

    if (orderRouteMapInstance) {
        orderRouteMapInstance.destroy();
    }

    const mapContainer = document.getElementById('orderRouteMap');

    if (!pathCoordinates || pathCoordinates.length === 0) {
        mapContainer.innerHTML = '<p class="text-center p-3">无有效路径数据显示。</p>';
        return;
    }

    mapContainer.innerHTML = '';
    orderRouteMapInstance = new AMap.Map('orderRouteMap', {
        resizeEnable: true,
        zoom: 11,
        center: pathCoordinates[0]
    });

    const polyline = new AMap.Polyline({
        path: pathCoordinates,
        strokeColor: "#0d6efd",
        strokeOpacity: 0.9,
        strokeWeight: 6,
        strokeStyle: "solid",
        showDir: true
    });

    orderRouteMapInstance.add(polyline);

    if (pathCoordinates.length > 0) {
        // 起点标记
        const startMarker = new AMap.Marker({
            position: new AMap.LngLat(pathCoordinates[0][0], pathCoordinates[0][1]),
            title: '起点',
            icon: 'https://webapi.amap.com/theme/v1.3/markers/n/start.png'
        });
        
        // 终点标记
        const endMarker = new AMap.Marker({
            position: new AMap.LngLat(
                pathCoordinates[pathCoordinates.length-1][0], 
                pathCoordinates[pathCoordinates.length-1][1]
            ),
            title: '终点',
            icon: 'https://webapi.amap.com/theme/v1.3/markers/n/end.png'
        });
        
        orderRouteMapInstance.add([startMarker, endMarker]);
        
        // 自动调整视图以包含所有标记和路线
        orderRouteMapInstance.setFitView();
    }
}

// 辅助函数：格式化日期
function formatDate(dateString, isRegistrationDate = false) {
    if (!dateString) return '暂无日期信息';
    
    const date = new Date(dateString);
    const now = new Date();
    
    // 如果是注册时间且在当前时间之前注册的，统一显示为2025-5-16
    if (isRegistrationDate && date < now) {
        return '2025-05-16 00:00:00';
    }
    
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    });
}

// 辅助函数：格式化地址
function formatAddress(addressInfo) {
    if (!addressInfo) return '暂无地址信息';
    const name = addressInfo.name || '未提供姓名';
    const phone = addressInfo.phone || '未提供电话';
    const address = addressInfo.detailAddress || '未提供详细地址';
    return `${name} ${phone}<br>${address}`;
}

// 辅助函数：获取订单状态对应的徽章类
function getOrderStatusBadgeClass(status) {
    switch (status) {
        case 'PENDING':
            return 'bg-secondary';
        case 'PENDING_COLLECTION':
            return 'bg-info';
        case 'COLLECTED':
            return 'bg-primary';
        case 'IN_TRANSIT':
            return 'bg-primary';
        case 'OUT_FOR_DELIVERY':
            return 'bg-warning';
        case 'DELIVERED':
            return 'bg-success';
        case 'SIGNED':
            return 'bg-success';
        case 'COMPLETED':
            return 'bg-success';
        case 'CANCELLED':
            return 'bg-danger';
        case 'DELIVERY_FAILED':
            return 'bg-danger';
        default:
            return 'bg-secondary';
    }
}

// 辅助函数：获取配送员状态对应的徽章类
function getStatusBadgeClass(status) {
    switch (status) {
        case 'IDLE':
            return 'bg-info';
        case 'DELIVERING':
            return 'bg-primary';
        case 'BUSY':
            return 'bg-warning';
        case 'OFFLINE':
            return 'bg-secondary';
        default:
            return 'bg-secondary';
    }
}

// 辅助函数：获取配送员状态对应的指示器类
function getStatusIndicatorClass(status) {
    switch (status) {
        case 'IDLE':
            return 'status-idle';
        case 'DELIVERING':
            return 'status-online';
        case 'BUSY':
            return 'status-busy';
        case 'OFFLINE':
            return 'status-offline';
        default:
            return 'status-offline';
    }
}

// 辅助函数：格式化订单状态
function formatOrderStatus(status) {
    switch (status) {
        case 'PENDING':
            return '待处理';
        case 'PENDING_PAYMENT':
            return '待支付';
        case 'PENDING_COLLECTION':
            return '待揽收';
        case 'COLLECTED':
            return '已揽收';
        case 'IN_TRANSIT':
            return '运输中';
        case 'TRANSPORTING':
            return '运输中';
        case 'OUT_FOR_DELIVERY':
            return '派送中';
        case 'DELIVERED':
            return '已送达';
        case 'SIGNED':
            return '已签收';
        case 'COMPLETED':
            return '已完成';
        case 'CANCELLED':
            return '已取消';
        case 'DELIVERY_FAILED':
            return '派送失败';
        case 'REFUNDED':
            return '已退款';
        default:
            return status || '未知状态';
    }
}

// 辅助函数：格式化配送员状态
function formatDeliveryPersonStatus(status) {
    switch (status) {
        case 'IDLE':
            return '空闲';
        case 'DELIVERING':
            return '配送中';
        case 'BUSY':
            return '忙碌';
        case 'OFFLINE':
            return '离线';
        default:
            return status || '未知状态';
    }
}

// 辅助函数：显示提示信息
function showAlert(message, type = 'info') {
    alertArea.innerHTML = `
        <div class="alert alert-${type} alert-dismissible fade show" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    `;
    alertArea.style.display = 'block';

    // 5秒后自动关闭
    setTimeout(() => {
        const alert = alertArea.querySelector('.alert');
        if (alert) {
            const bsAlert = new bootstrap.Alert(alert);
            bsAlert.close();
        }
    }, 5000);
}

// 辅助函数：显示/隐藏加载指示器
function showLoader(show) {
    mainLoader.style.display = show ? 'flex' : 'none';
}

// 辅助函数：带认证的API请求
async function fetchAuthenticatedApi(url, options = {}) {
    const defaultOptions = {
        headers: {
            'Content-Type': 'application/json'
        },
        credentials: 'same-origin'
    };

    const mergedOptions = {
        ...defaultOptions,
        ...options,
        headers: {
            ...defaultOptions.headers,
            ...options.headers
        }
    };

    return fetch(url, mergedOptions);
}

// 添加全局变量
let stompClient = null;
let newOrdersMap = new Map(); // 存储新订单
const newOrdersArea = document.getElementById('newOrdersArea');
const newOrdersList = document.getElementById('newOrdersList');
const closeNewOrdersBtn = document.getElementById('closeNewOrdersBtn');

// 在初始化页面函数中添加WebSocket连接
async function initPage() {
    showLoader(true);
    try {
        // 获取当前配送员信息
        await fetchDeliveryPersonInfo();
        // 初始化当前位置地图
        initCurrentLocationMap();
        // 加载订单列表
        await loadMyOrders();
        // 加载可接单订单列表
        await loadAvailableOrders();
        // 连接WebSocket
        connectWebSocket();
        // 默认显示订单列表视图
        showMyOrdersView();
    } catch (error) {
        console.error('初始化页面失败:', error);
        showAlert('初始化页面失败，请刷新页面重试。', 'danger');
    } finally {
        showLoader(false);
    }
}

// 添加WebSocket连接函数
function connectWebSocket() {
    const socket = new SockJS('/ws');
    stompClient = Stomp.over(socket);
    
    stompClient.connect({}, function(frame) {
        console.log('Connected to WebSocket: ' + frame);
        
        // 订阅新订单通知
        stompClient.subscribe('/topic/orders/new', function(message) {
            const notification = JSON.parse(message.body);
            handleNewOrderNotification(notification);
        });
        
        // 可以添加其他订阅，如订单状态变更等
    }, function(error) {
        console.error('WebSocket连接失败:', error);
        setTimeout(connectWebSocket, 5000); // 5秒后重连
    });
}

// 处理新订单通知
function handleNewOrderNotification(notification) {
    console.log('收到新订单通知:', notification);
    
    // 如果配送员状态不是空闲，不显示新订单
    if (currentDeliveryPerson && currentDeliveryPerson.status !== 'IDLE') {
        console.log('配送员当前状态不是空闲，忽略新订单');
        return;
    }
    
    // 存储新订单
    newOrdersMap.set(notification.orderNumber, notification);
    
    // 更新新订单列表UI
    updateNewOrdersUI();
    
    // 显示通知
    showAlert(`收到新订单: ${notification.orderNumber}`, 'info');
    
    // 播放提示音（可选）
    playNotificationSound();
}

// 更新新订单列表UI
function updateNewOrdersUI() {
    if (newOrdersMap.size === 0) {
        newOrdersArea.style.display = 'none';
        newOrdersList.innerHTML = '<p class="text-center text-muted">正在等待新订单...</p>';
        return;
    }
    
    newOrdersArea.style.display = 'block';
    
    const ordersHtml = Array.from(newOrdersMap.values()).map(order => `
        <div class="card mb-2 new-order-card">
            <div class="card-header bg-light d-flex justify-content-between align-items-center">
                <h6 class="mb-0">订单号: ${order.orderNumber}</h6>
                <span class="badge bg-warning text-dark">待接单</span>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <p class="mb-1 small"><i class="bi bi-box-seam me-1"></i><strong>物品:</strong> ${order.itemDescription || 'N/A'}</p>
                        <p class="mb-1 small"><i class="bi bi-rulers me-1"></i><strong>重量:</strong> ${order.weight ? order.weight + ' kg' : 'N/A'}</p>
                    </div>
                    <div class="col-md-6">
                        <p class="mb-1 small"><i class="bi bi-calendar-plus me-1"></i><strong>创建时间:</strong> ${formatDate(order.creationTime)}</p>
                        <p class="mb-1 small"><i class="bi bi-cash-coin me-1"></i><strong>费用:</strong> ${order.calculatedFee ? '¥' + order.calculatedFee.toFixed(2) : 'N/A'}</p>
                    </div>
                </div>
                <div class="row mt-1">
                    <div class="col-md-6">
                        <p class="mb-1 small"><i class="bi bi-person-up me-1"></i><strong>发货方:</strong> ${formatAddress(order.shipperInfo)}</p>
                    </div>
                    <div class="col-md-6">
                        <p class="mb-1 small"><i class="bi bi-person-down me-1"></i><strong>收货方:</strong> ${formatAddress(order.recipientInfo)}</p>
                    </div>
                </div>
                <div class="text-end mt-2">
                    <button class="btn btn-sm btn-success accept-order-btn" data-order-number="${order.orderNumber}">
                        <i class="bi bi-check-circle"></i> 接单
                    </button>
                </div>
            </div>
        </div>
    `).join('');
    
    newOrdersList.innerHTML = ordersHtml;
    
    // 添加接单按钮点击事件
    document.querySelectorAll('.accept-order-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const orderNumber = this.getAttribute('data-order-number');
            acceptOrder(orderNumber);
        });
    });
}

// 接单函数
async function acceptOrder(orderNumber) {
    showLoader(true);
    try {
        const response = await fetchAuthenticatedApi(
            `${API_BASE_URL}/orders/${orderNumber}/accept`,
            {
                method: 'POST'
            }
        );

        if (response.ok) {
            const updatedOrder = await response.json();
            showAlert('接单成功！', 'success');
            
            // 从新订单列表中移除
            newOrdersMap.delete(orderNumber);
            updateNewOrdersUI();
            
            // 重新加载我的订单列表
            await loadMyOrders();
        } else {
            const errorData = await response.json();
            throw new Error(errorData || '接单失败');
        }
    } catch (error) {
        console.error('接单失败:', error);
        showAlert('接单失败: ' + error.message, 'danger');
    } finally {
        showLoader(false);
    }
}

// 播放提示音函数（可选）
function playNotificationSound() {
    try {
        const audio = new Audio('/sounds/notification.mp3');
        audio.play();
    } catch (e) {
        console.warn('无法播放提示音:', e);
    }
}

// 添加关闭新订单区域按钮事件
closeNewOrdersBtn.addEventListener('click', function() {
    newOrdersArea.style.display = 'none';
});

// 加载可接单订单
async function loadAvailableOrders() {
    availableOrdersLoader.style.display = 'block';
    noAvailableOrdersMessage.style.display = 'none';
    availableOrdersList.innerHTML = '';

    try {
        const response = await fetchAuthenticatedApi(`${API_BASE_URL}/available-orders`);
        if (response.ok) {
            const orders = await response.json();
            displayAvailableOrders(orders);
        } else {
            throw new Error('获取可接单列表失败');
        }
    } catch (error) {
        console.error('获取可接单列表失败:', error);
        showAlert('获取可接单列表失败，请刷新页面重试。', 'danger');
    } finally {
        availableOrdersLoader.style.display = 'none';
    }
}

// 显示可接单订单列表
function displayAvailableOrders(orders) {
    if (!orders || orders.length === 0) {
        noAvailableOrdersMessage.style.display = 'block';
        return;
    }

    const ordersHtml = orders.map(order => `
        <div class="card order-card">
            <div class="card-header bg-light d-flex justify-content-between align-items-center">
                <h5 class="mb-0">订单号: ${order.orderNumber}</h5>
                <span class="badge ${getOrderStatusBadgeClass(order.status)}">${formatOrderStatus(order.status)}</span>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <p class="mb-2"><i class="bi bi-box-seam me-2"></i><strong>物品:</strong> ${order.itemDescription || 'N/A'}</p>
                        <p class="mb-2"><i class="bi bi-rulers me-2"></i><strong>重量:</strong> ${order.weight ? order.weight + ' kg' : 'N/A'}</p>
                    </div>
                    <div class="col-md-6">
                        <p class="mb-2"><i class="bi bi-calendar-plus me-2"></i><strong>创建时间:</strong> ${formatDate(order.creationTime)}</p>
                        <p class="mb-2"><i class="bi bi-cash-coin me-2"></i><strong>费用:</strong> ${order.calculatedFee ? '¥' + order.calculatedFee.toFixed(2) : 'N/A'}</p>
                    </div>
                </div>
                <div class="row mt-2">
                    <div class="col-12">
                        <div class="d-flex justify-content-between align-items-center">
                            <button class="btn btn-primary btn-sm" onclick="viewAvailableOrderDetails('${order.orderNumber}')">查看详情</button>
                            <button class="btn btn-success btn-sm" onclick="acceptOrder('${order.orderNumber}')">接单</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `).join('');

    availableOrdersList.innerHTML = ordersHtml;
}

// 显示可接单订单视图
function showAvailableOrdersView() {
    myOrdersView.style.display = 'none';
    orderDetailView.style.display = 'none';
    profileView.style.display = 'none';
    availableOrdersView.style.display = 'block';
    
    // 更新导航栏激活状态
    document.querySelectorAll('.nav-link').forEach(link => link.classList.remove('active'));
    availableOrdersLink.classList.add('active');
    
    // 刷新可接单订单列表
    loadAvailableOrders();
}

// 查看可接单订单详情
function viewAvailableOrderDetails(orderNumber) {
    // 可以复用现有的查看订单详情功能
    viewOrderDetail(orderNumber);
}

// 获取工作统计数据
async function loadWorkStatistics() {
    const workStatsElement = document.getElementById('workStats');
    
    try {
        const response = await fetchAuthenticatedApi(`${API_BASE_URL}/statistics`);
        if (response.ok) {
            const statistics = await response.json();
            displayWorkStatistics(statistics, workStatsElement);
        } else {
            throw new Error('获取工作统计数据失败');
        }
    } catch (error) {
        console.error('获取工作统计数据失败:', error);
        workStatsElement.innerHTML = `
            <div class="alert alert-danger" role="alert">
                <i class="bi bi-exclamation-triangle-fill me-2"></i>获取工作统计数据失败
            </div>
            <button class="btn btn-outline-primary btn-sm" onclick="loadWorkStatistics()">
                <i class="bi bi-arrow-clockwise me-1"></i>重试
            </button>
        `;
    }
}

// 显示工作统计数据
function displayWorkStatistics(statistics, element) {
    // 计算进度条宽度
    const completionRate = statistics.completionRate || 0;
    const progressWidth = completionRate + '%';
    
    // 获取各状态订单数量
    const pendingCollection = statistics.ordersByStatus?.PENDING_COLLECTION || 0;
    const collected = statistics.ordersByStatus?.COLLECTED || 0;
    const transporting = statistics.ordersByStatus?.TRANSPORTING || 0;
    const outForDelivery = statistics.ordersByStatus?.OUT_FOR_DELIVERY || 0;
    const signed = statistics.ordersByStatus?.SIGNED || 0;
    const completed = statistics.ordersByStatus?.COMPLETED || 0;
    const failed = statistics.ordersByStatus?.DELIVERY_FAILED || 0;
    
    // 生成HTML
    const html = `
        <div class="row mb-3">
            <div class="col-md-6">
                <div class="d-flex align-items-center mb-2">
                    <i class="bi bi-box-seam me-2 text-primary"></i>
                    <span>总订单数:</span>
                    <span class="ms-auto fw-bold">${statistics.totalOrders || 0}</span>
                </div>
                <div class="d-flex align-items-center mb-2">
                    <i class="bi bi-check-circle me-2 text-success"></i>
                    <span>已完成订单:</span>
                    <span class="ms-auto fw-bold">${statistics.completedOrders || 0}</span>
                </div>
                <div class="d-flex align-items-center">
                    <i class="bi bi-percent me-2 text-info"></i>
                    <span>完成率:</span>
                    <span class="ms-auto fw-bold">${completionRate}%</span>
                </div>
            </div>
            <div class="col-md-6">
                <div class="d-flex align-items-center mb-2">
                    <i class="bi bi-calendar-day me-2 text-primary"></i>
                    <span>今日订单:</span>
                    <span class="ms-auto fw-bold">${statistics.todayOrders || 0}</span>
                </div>
                <div class="d-flex align-items-center">
                    <i class="bi bi-check-circle me-2 text-success"></i>
                    <span>今日完成:</span>
                    <span class="ms-auto fw-bold">${statistics.todayCompletedOrders || 0}</span>
                </div>
            </div>
        </div>
        
        <div class="mb-3">
            <label class="form-label small">完成率</label>
            <div class="progress" style="height: 10px;">
                <div class="progress-bar bg-success" role="progressbar" style="width: ${progressWidth}" 
                    aria-valuenow="${completionRate}" aria-valuemin="0" aria-valuemax="100">${completionRate}%</div>
            </div>
        </div>
        
        <div>
            <label class="form-label small">订单状态分布</label>
            <div class="row g-2 text-center">
                <div class="col-4">
                    <div class="border rounded p-2">
                        <div class="small text-muted">待取件</div>
                        <div class="fw-bold">${pendingCollection}</div>
                    </div>
                </div>
                <div class="col-4">
                    <div class="border rounded p-2">
                        <div class="small text-muted">已取件</div>
                        <div class="fw-bold">${collected}</div>
                    </div>
                </div>
                <div class="col-4">
                    <div class="border rounded p-2">
                        <div class="small text-muted">运输中</div>
                        <div class="fw-bold">${transporting}</div>
                    </div>
                </div>
                <div class="col-4">
                    <div class="border rounded p-2">
                        <div class="small text-muted">派送中</div>
                        <div class="fw-bold">${outForDelivery}</div>
                    </div>
                </div>
                <div class="col-4">
                    <div class="border rounded p-2">
                        <div class="small text-muted">已签收</div>
                        <div class="fw-bold">${signed}</div>
                    </div>
                </div>
                <div class="col-4">
                    <div class="border rounded p-2">
                        <div class="small text-muted">已完成</div>
                        <div class="fw-bold">${completed}</div>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    element.innerHTML = html;
}